// Copyright (c) 2021 Presto Labs Pte. Ltd.
// Author: daniel

#include "coin2/exchange/lmax_digital/api_order/native_rest_async_asio_subscriber.h"

#include <cstdlib>
#include <iostream>
#include <sstream>
#include <string>
#include <thread>

#include <nlohmann/json.hpp>

#include "coin2/base/log.h"

namespace coin2::exchange::lmax_digital::api_order {

void LmaxdigitalRestAsyncAsioSubscriber::QueryAuthToken() {
  auto http_context = rest_client()->QueryAuth();
  if (!http_context) {
    return;
  }
  http_context->handler =
      std::bind(&LmaxdigitalRestAsyncAsioSubscriber::HandleQuery, this, std::placeholders::_1);
  http_driver_->PostAsyncContext(http_context);
}

void LmaxdigitalRestAsyncAsioSubscriber::QueryBalance() {
  auto http_context = rest_client()->QueryAccountBalance();
  if (!http_context) {
    return;
  }
  http_context->handler =
      std::bind(&LmaxdigitalRestAsyncAsioSubscriber::HandleQuery, this, std::placeholders::_1);
  http_driver_->PostAsyncContext(http_context);
}

// TODO(daniel): to confirm
// from lmax support, maker order will not be showed up in the account
// and from the rest api spec, looks only stop limit order will be list
void LmaxdigitalRestAsyncAsioSubscriber::QueryOpenOrders() {
  auto http_context = rest_client()->QueryOpenOrders();
  if (!http_context) {
    return;
  }
  http_context->handler =
      std::bind(&LmaxdigitalRestAsyncAsioSubscriber::HandleQuery, this, std::placeholders::_1);
  http_driver_->PostAsyncContext(http_context);
}

void LmaxdigitalRestAsyncAsioSubscriber::SubscribeAsync() {
  AddPeriodicTask(
      std::bind(&LmaxdigitalRestAsyncAsioSubscriber::QueryAuthToken, this),
      5,
      "query_auth");

  AddPeriodicTask(
      std::bind(&LmaxdigitalRestAsyncAsioSubscriber::QueryBalance, this),
      config_.query_account_balance_period_sec(),
      "query_balance");

  AddPeriodicTask(
      std::bind(&LmaxdigitalRestAsyncAsioSubscriber::QueryOpenOrders, this),
      config_.query_open_orders_period_sec(),
      "query_open_orders");
}

}  // namespace coin2::exchange::lmax_digital::api_order
